<?php

namespace wechat;

/**
 * 微信类实现
 * @author zhoujj <sczhoujj@qq.com>
 */
require_once dirname(__FILE__) . '/lib/fnc.php';

class Wechat {

    /**
     * 单例储存对象
     */
    protected static $instance;

    /**
     * 子类实例存在对象
     */
    protected $child = [];

    /**
     * 微信appid
     */
    protected $appid;

    /**
     * 微信 appsecret
     */
    protected $appsecret;

    /**
     * 错误代码
     */
    protected $errcode = 0;

    /**
     * 错误信息
     */
    protected $errmsg = "";

    /**
     * 构建方法
     * @param string $appid 微信APPID
     * @param string $appsecret 微信密钥
     */
    public function __construct($appid, $appsecret) {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
    }

    /**
     * 取得微信SDK类实例
     * @access public
     * @param string $appid 微信APPID
     * @param string $appsecret 微信密钥
     * @param  bool|string   $name 连接标识 true 强制重新实例化
     * @return Class
     */
    public static function instance($appid, $appsecret, $name = false) {
        if (false === $name) {
            $name = md5(serialize($appid));
        }
        if (true === $name || !isset(self::$instance[$name])) {
            if (true === $name) {
                $name = md5(serialize($appid));
            }
            self::$instance[$name] = new self($appid, $appsecret);
        }
        return self::$instance[$name];
    }

    /**
     * 调用子类返回并返回对应子类
     * @param 子类名称 $name
     * @param 默认参数 $arguments
     */
    public function __call($name, $arguments = null) {
        $className = ucfirst(strtolower($name));
        $classPath = "\\wechat\\src\\{$className}";
        if (class_exists($classPath)) {
            $childName = md5($classPath);
            if (!isset($this->child[$childName])) {
                $childModel = new $classPath($arguments);
                $childModel->wechat = $this;
                $this->child[$childName] = $childModel;
            }
            return $this->child[$childName];
        } else {
            $this->setError(101, "对应子类不存在");
            return false;
        }
    }

    /**
     * 动态设置类属性
     * @param string $name 属性名称
     * @param mixed $value 属性值
     */
    public function __set($name, $value) {
        $this->$name = $value;
    }

    /**
     * 取得动态设置的属性值
     */
    public function __get($name) {
        if (empty($this->$name)) {
            return "";
        }
        return $this->$name;
    }

    /**
     * 错误信息设置
     */
    protected function setError($code, $msg) {
        $this->errcode = $code;
        $this->errmsg = $msg;
    }

    /**
     * 获取错误编码
     */
    public function getErrCode() {
        return $this->errcode;
    }

    /**
     * 获取错误信息
     */
    public function getErrMsg() {
        return $this->errmsg;
    }

}
